/*
 * @Descripttion:
 * @version:
 * @Author: liwanpeng
 * @Date: 2020-12-02 13:45:18
 * @LastEditors: sueRimn
 * @LastEditTime: 2020-12-03 11:19:34
 */
// 获取图片base64编码
export function getBase64Image(img) {
  var canvas = document.createElement("canvas")
  canvas.width = img.width
  canvas.height = img.height
  var ctx = canvas.getContext("2d")
  ctx.drawImage(img, 0, 0, img.width, img.height)
  var dataURL = canvas.toDataURL("image/png")
  return dataURL
}
// 转换图片文件
export function base64ImgtoFile(dataurl, filename = "file") {
  let arr = dataurl.split(",")
  let mime = arr[0].match(/:(.*?);/)[1]
  let suffix = mime.split("/")[1]
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], `${filename}.${suffix}`, {
    type: mime
  })
}
// 获取文件大小
export function readFileSizeUnit(file, unit) {
  let UNITS = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
  let STEP = 1024
  let size = file.size
  var value = parseFloat(size, 10)
  var unitIndex = UNITS.indexOf(unit)
  if (unitIndex <= -1) {
    return -1
  } else if (unitIndex > 0) {
    return (value / Math.pow(STEP, unitIndex)).toFixed(2)
  }
}

export function bufferToBase64(buffer) {
  return btoa(new Uint8Array(buffer).reduce((data, byte) => data + String.fromCharCode(byte), ''))
}

